import React, { useEffect, useState, useRef } from 'react'
import { axiosConfig, backIP, error, success } from './config'
import axios from 'axios'
import cookies from 'react-cookies'
import styles from '../../styles/common/header.scss'
import { Drawer, Button } from 'antd';
import UserDataShow from './UserDataShow'
import Router from 'next/router'
import { getToken, commonReply } from './util'
import store from '../redux/store'
import AlterPassword from './AlterPassword'

export interface userDataConfig {
    number?: string,
    real_name?: string,
    jurisdiction?: string,
    avatar?: string,
    identify?: string,
    college?: string,
    grade?: string,
    class?: string,
}

const userDataTitle = {
    number: '学号',
    real_name: '姓名',
    identify: '身份',
    college: '学院',
    grade: '年级',
    class: '班级'
}

export default function Header(props) {
    const [userData, setUserData] = useState<userDataConfig>({})
    const [userDataIsChange, setUserDataIsChange] = useState(true)
    const [visible, setVisible] = useState(false);
    const avatarRef = useRef();
    const [modalVisible, setModalVisible] = useState(false)

    const showDrawer = () => {
        setVisible(true);
    };
    const onClose = () => {
        setVisible(false);
        setUserDataIsChange(true)
    };
    const saveUserDataInStore = async (token: string) => {
        const { data: res }: { data: axiosConfig } = await axios.get(`${backIP}/user`, {
            headers: {
                Authorization: token
            }
        })
        props.transform_user(res.data)
        setUserData(res.data)
    }
    const uploadAvatar = async () => {
        const token: string = getToken();
        if (!token) {
            error('token已失效，请重新登录')
        }
        const formData = new FormData()
        formData.append('uploadfile', (avatarRef.current as any).files[0])
        const { data: res }: { data: axiosConfig } = await axios({
            url: `${backIP}/avatar`, // 此处填上服务器对应的地址（有路由把路由加上）
            method: 'put',
            data: formData,
            headers: { 'Content-Type': 'multipart/form-data', Authorization: token }  // 一定要设置请求头类型为'multipart/form-data'，否则nodejs会解析错误
        })
        console.log(res)
        if (res.code === 0) {
            setUserData({
                ...userData,
                avatar: res.data
            })
            setUserDataIsChange(false)
        } else {
            error(res.message);
        }
    }
    const handleExit = () => {
        success('成功退出，将在1秒后返回登录界面')
        cookies.remove('Authorization')
        props.remove_user()
        setTimeout(() => {
            Router.push('/');
        }, 1000);
    }
    const handleSubmitAvatar = async () => {
        const token: string = getToken();
        const { data: res }: { data: axiosConfig } = await axios.post(`${backIP}/avatar`, {
            avatar: userData.avatar
        }, {
            headers: {
                Authorization: token
            }
        })
        commonReply(res);
        if (res.code === 0) {
            setUserDataIsChange(true)
        }
    }

    useEffect(() => {
        const token: string = getToken();
        if (token) {
            // 说明为空对象，则向后端请求数据
            if (JSON.stringify(store.getState()) === "{}") {
                saveUserDataInStore(token)
            } else {
                setUserData(store.getState())
            }
        } else {
            Router.push('/')
        }
    }, [])
    return (
        <>
            <div className={styles.layout}>
                <p className={styles.title} onClick={() => { Router.push('/home') }}>教室信息管理系统</p>
                <img
                    src={userData.avatar}
                    alt="头像"
                    className={styles.avatar}
                    onClick={showDrawer}
                />
            </div>
            <Drawer
                placement="right"
                closable={false}
                onClose={onClose}
                visible={visible}
                width={400}
            >
                <div className={styles.userShow}>
                    <img
                        src={userData.avatar}
                        alt="头像"
                        className={styles.avatar}
                    />
                    <input
                        type="file"
                        ref={avatarRef}
                        className={styles.fileInput}
                        onChange={uploadAvatar}
                    />
                    {
                        Object.keys(userData).map((key, index) => {
                            if (key !== 'jurisdiction' && key !== 'avatar') {
                                return <UserDataShow
                                    value={userData[key]}
                                    key={index}
                                    title={userDataTitle[key]}
                                />
                            }
                        })
                    }
                    <Button
                        type="primary"
                        className={styles.btn}
                        onClick={() => { setModalVisible(true) }}
                    >
                        修改密码
                    </Button>
                    <br />
                    <Button
                        type="primary"
                        className={styles.btn}
                        disabled={userDataIsChange}
                        onClick={handleSubmitAvatar}
                    >
                        提交头像
                    </Button>
                    <br />
                    <Button
                        type="primary"
                        danger
                        className={styles.btn}
                        onClick={handleExit}
                    >
                        退出登录
                    </Button>
                    <AlterPassword
                        visiable={modalVisible}
                        setVisiable={setModalVisible}
                    />
                </div>
            </Drawer>
        </>
    )
}
